package edu.sandau.app.basic.controller;

import edu.sandau.app.basic.vo.BasicMsg;
import edu.sandau.app.basic.vo.BasicMsgWithData;
import edu.sandau.app.basic.golbal.GlobalEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/files")
@Tag(name = "文件管理", description = "文件上传和下载接口")
public class FileController {

    @Value("${spring.web.resources.static-locations:classpath:/static/}")
    private String staticLocation;
    
    // 使用项目外的固定目录，避免重启后丢失
    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "上传图片文件到服务器")
    @ApiResponse(responseCode = "200", description = "上传成功")
    public BasicMsgWithData<String> uploadFile(
            @Parameter(description = "上传的文件") @RequestParam("file") MultipartFile file) {
        BasicMsgWithData<String> msg = new BasicMsgWithData<>();
        
        try {
            if (file.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.FILE_UPLOAD_FAIL);
                msg.setErrorMsg("文件不能为空");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                msg.setErrorCode(GlobalEnum.ErrorCode.FILE_UPLOAD_FAIL);
                msg.setErrorMsg("只支持图片文件");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + extension;

            // 创建上传目录 - 使用项目外的固定目录，避免重启后丢失
            File dir = new File(UPLOAD_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 保存文件
            Path filePath = Paths.get(UPLOAD_DIR + filename);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件访问URL
            String fileUrl = "/uploads/" + filename;
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("上传成功");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            msg.setData(fileUrl);

        } catch (IOException e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FILE_UPLOAD_FAIL);
            msg.setErrorMsg("文件上传失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }

        return msg;
    }

    @GetMapping("/check/{filename}")
    @Operation(summary = "检查文件是否存在")
    public BasicMsg checkFile(@PathVariable String filename) {
        BasicMsg msg = new BasicMsg();
        try {
            File file = new File(UPLOAD_DIR + filename);
            
            if (file.exists()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("文件存在");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.FILE_UPLOAD_FAIL);
                msg.setErrorMsg("文件不存在: " + file.getAbsolutePath());
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FILE_UPLOAD_FAIL);
            msg.setErrorMsg("检查失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
}
